package cn.iocoder.yudao.module.jikong.controller.admin.jkProduct;

import cn.hutool.json.JSONObject;
import cn.iocoder.yudao.module.jikong.controller.admin.jkProductType.vo.JkProductTypePageReqVO;
import cn.iocoder.yudao.module.jikong.controller.admin.project.vo.JkProjectPageReqVO;
import cn.iocoder.yudao.module.jikong.controller.admin.resource.vo.JkResourcePageReqVO;
import cn.iocoder.yudao.module.jikong.controller.admin.size.vo.JkSizePageReqVO;
import cn.iocoder.yudao.module.jikong.dal.dataobject.jkProductType.JkProductTypeDO;
import cn.iocoder.yudao.module.jikong.dal.dataobject.project.JkProjectDO;
import cn.iocoder.yudao.module.jikong.dal.dataobject.resource.JkResourceDO;
import cn.iocoder.yudao.module.jikong.dal.dataobject.size.JkSizeDO;
import cn.iocoder.yudao.module.jikong.service.jkProductType.JkProductTypeService;
import cn.iocoder.yudao.module.jikong.service.project.JkProjectService;
import cn.iocoder.yudao.module.jikong.service.resource.JkResourceService;
import cn.iocoder.yudao.module.jikong.service.size.JkSizeService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.jikong.controller.admin.jkProduct.vo.*;
import cn.iocoder.yudao.module.jikong.dal.dataobject.jkProduct.JkProductDO;
import cn.iocoder.yudao.module.jikong.service.jkProduct.JkProductService;

@Tag(name = "管理后台 - 疾控产品表")
@RestController
@RequestMapping("/jikong/jk-product")
@Validated
public class JkProductController {

    @Resource
    private JkProductService jkProductService;
    @Resource
    private JkProductTypeService jkProductTypeService;
    @Resource
    private JkResourceService jkResourceService;
    @Resource
    private JkProjectService jkProjectService;
    @Resource
    private JkSizeService jkSizeService;

    @PostMapping("/create")
    @Operation(summary = "创建疾控产品表")
    @PreAuthorize("@ss.hasPermission('jikong:jk-product:create')")
    public CommonResult<Long> createJkProduct(@Valid @RequestBody JkProductSaveReqVO createReqVO) {
        return success(jkProductService.createJkProduct(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新疾控产品表")
    @PreAuthorize("@ss.hasPermission('jikong:jk-product:update')")
    public CommonResult<Boolean> updateJkProduct(@Valid @RequestBody JkProductSaveReqVO updateReqVO) {
        jkProductService.updateJkProduct(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除疾控产品表")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('jikong:jk-product:delete')")
    public CommonResult<Boolean> deleteJkProduct(@RequestParam("id") Long id) {
        jkProductService.deleteJkProduct(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除疾控产品表")
                @PreAuthorize("@ss.hasPermission('jikong:jk-product:delete')")
    public CommonResult<Boolean> deleteJkProductList(@RequestParam("ids") List<Long> ids) {
        jkProductService.deleteJkProductListByIds(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得疾控产品表")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('jikong:jk-product:query')")
    public CommonResult<JkProductRespVO> getJkProduct(@RequestParam("id") Long id) {
        JkProductDO jkProduct = jkProductService.getJkProduct(id);
        JkProductRespVO bean = BeanUtils.toBean(jkProduct, JkProductRespVO.class);
        bean.setTypeName(jkProductTypeService.getJkProductType(bean.getTypeId()).getName());
        return success(bean);
    }

    @GetMapping("/page")
    @Operation(summary = "获得疾控产品表分页")
    @PreAuthorize("@ss.hasPermission('jikong:jk-product:query')")
    public CommonResult<PageResult<JkProductRespVO>> getJkProductPage(@Valid JkProductPageReqVO pageReqVO) {
        PageResult<JkProductDO> pageResult = jkProductService.getJkProductPage(pageReqVO);
        PageResult<JkProductRespVO> bean = BeanUtils.toBean(pageResult, JkProductRespVO.class);

        //查询所有的产品分类
        JkProductTypePageReqVO jkProductTypePageReqVO = new JkProductTypePageReqVO();
        jkProductTypePageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        //key为id，value为name
        Map<Long, String> productTypeMap = jkProductTypeService.getJkProductTypePage(jkProductTypePageReqVO).getList()
                .stream().collect(Collectors.toMap(JkProductTypeDO::getId, JkProductTypeDO::getName));

        //查询所有的项目
        JkProjectPageReqVO jkProductTypePageReqVO1 = new JkProjectPageReqVO();
        jkProductTypePageReqVO1.setPageSize(PageParam.PAGE_SIZE_NONE);
        //key为id，value为name
        Map<Long, String> projectMap = jkProjectService.getJkProjectPage(jkProductTypePageReqVO1).getList()
                .stream().collect(Collectors.toMap(JkProjectDO::getId, JkProjectDO::getName));

        //查询所有的规格
        JkSizePageReqVO jkProductTypePageReqVO2 = new JkSizePageReqVO();
        jkProductTypePageReqVO2.setPageSize(PageParam.PAGE_SIZE_NONE);
        //key为id，value为name
        Map<Long, String> specMap = jkSizeService.getJkSizePage(jkProductTypePageReqVO2).getList()
                .stream().collect(Collectors.toMap(JkSizeDO::getId, JkSizeDO::getName));

        //查询所有的来源
        JkResourcePageReqVO jkProductTypePageReqVO3 = new JkResourcePageReqVO();
        jkProductTypePageReqVO3.setPageSize(PageParam.PAGE_SIZE_NONE);
        //key为id，value为name
        Map<Long, String> sourceMap = jkResourceService.getJkResourcePage(jkProductTypePageReqVO3).getList()
                .stream().collect(Collectors.toMap(JkResourceDO::getId, JkResourceDO::getName));

        //设置typeName
        bean.getList().forEach(item -> {
            item.setTypeName(productTypeMap.get(item.getTypeId()));
            item.setProjectName(projectMap.get(item.getProjectId()));
            item.setSizeName(specMap.get(item.getSizeId()));
            item.setResourceName(sourceMap.get(item.getResourceId()));
        });
        return success(bean);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出疾控产品表 Excel")
    @PreAuthorize("@ss.hasPermission('jikong:jk-product:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportJkProductExcel(@Valid JkProductPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<JkProductDO> list = jkProductService.getJkProductPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "疾控产品表.xls", "数据", JkProductRespVO.class,
                        BeanUtils.toBean(list, JkProductRespVO.class));
    }

    @GetMapping("/statistics-by-type")
    @Operation(summary = "根据产品类型获取疾控产品数量的统计接口")
    public CommonResult<List<JSONObject>> statisticsByProductType(){
        //返回一个jsonList，里面的jsonobject，name为产品名称，value为个数，随机生成一些（name为疾控相关的一些分类）
        //查询样本分类列表
        JkProductTypePageReqVO pageReqVO = new JkProductTypePageReqVO();
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<JkProductTypeDO> list = jkProductTypeService.getJkProductTypePage(pageReqVO).getList();
        List<JSONObject> jsonList = new ArrayList<>();
        for (JkProductTypeDO jkProductTypeDO : list) {
             JSONObject jsonObject = new JSONObject();
             jsonObject.set("name", jkProductTypeDO.getName());
             // 使用固定的哈希值生成固定的产品数量，确保每次调用接口时相同产品类型返回相同数量
             int fixedValue = Math.abs(jkProductTypeDO.getName().hashCode()) % 10000;
             jsonObject.set("value", fixedValue);
             jsonList.add(jsonObject);
        }
        return success(jsonList);
    }



}
